package com.tulele.vtool.wechat.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.tulele.vtool.config.JinPaiDataConfig;
import com.tulele.vtool.mapper.ImportUsersJinpaiMapper;
import com.tulele.vtool.mapper.SysGzhMapper;
import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.UserBrandCombinedInfo;
import com.tulele.vtool.model.combinedEntity.WxPushUserInfo;
import com.tulele.vtool.service.*;
import com.tulele.vtool.task.async.ArticleAsyncTask;
import com.tulele.vtool.task.async.UserAsyncTask;
import com.tulele.vtool.task.async.UserSaveArticleInfoWxPushAsyncTask;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.WeChatUserSubscribeScene;
import com.tulele.vtool.wechat.builder.TextBuilder;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.*;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.sql.ResultSet;
import java.util.*;

//关注时触发
@Component
@Slf4j
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private UserAsyncTask userAsyncTask;

    @Autowired
    private ArticleAsyncTask articleAsyncTask;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    @Lazy
    protected MenuHandler menuHandler;

    @Autowired
    @Lazy
    protected MsgHandler msgHandler;

    @Autowired
    private WantedUsersService wantedUsersService;

    @Autowired
    @Lazy
    private UserSaveArticleInfoWxPushAsyncTask userSaveArticleInfoWxPushAsyncTask;

//    @Autowired
//    private PlatformSysInfoConfig platformSysInfoConfig;

    @Autowired
    private IUserPromotionSettleInfoService userPromotionSettleInfoService;

//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    //开放平台用户分组标识
//    @Value("${openGroupCode}")
//    private String openGroupCode;

    @Autowired
    private ImportUsersService importUsersService;

    @Autowired
    private IVipInfoService vipInfoService;

    @Autowired
    private ILookArticleInfoService iLookArticleInfoService;

    @Autowired
    private IUserRelateArticleTypeInfoService iUserRelateArticleTypeInfoService;

//    @Value("${platform.frontDomain}")
//    private String frontDomain;

    @Value("${Professional}")
    private String professional;

//    @Autowired
//    private SysGzhMapper sysGzhMapper;

    @Autowired
    private JinPaiDataConfig jinPaiDataConfig;

    @Autowired
    private ImportUsersJinpaiMapper importUsersJinpaiMapper;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserPunchClockInfoService userPunchClockInfoService;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    @SneakyThrows
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {

        try {
            UserOpenIds userOpenId = new UserOpenIds();
            if (wxMpService != null && wxMpService.getWxMpConfigStorage() != null) {
                userOpenId.setGzhCode(wxMpService.getWxMpConfigStorage().getAppId());
            }
            if (wxMessage != null) {
                String fromUser = wxMessage.getFromUser();
                userOpenId.setOpenId(fromUser);

                if (wxMpService != null && wxMpService.getWxMpConfigStorage() != null) {
                    WxMpUser wxMpUser = wxMpService.getUserService().userInfo(fromUser);// 根据 openid 获取用户信息
                    String subscribeScene = wxMpUser.getSubscribeScene();// 用户订阅公众号的场景
                    userOpenId.setSubscribeScene(WeChatUserSubscribeScene.getSubscribeSceneText(subscribeScene));// 设置用户关注公众号的场景
                }
            }
            userOpenId.setType(1);
            userOpenId.setSubscribeTime(new Date());
            userInfoService.addUserOpenIds(userOpenId);
        } catch (Exception e) {
            log.error("*****  SubscribeHandler addUserOpenIds : " + e.getMessage());
        }

//        log.error("newSubscriberOpenId: " + wxMessage.getFromUser()
//                + " **********  eventKey: " + wxMessage.getEventKey());

        WeixinServiceDL weixinService = (WeixinServiceDL) wxMpService;
        PlatformSysInfo platformSysInfoConfig = sysGzhService.getPlatformSysInfoByAppId(weixinService.getWxMpConfigStorage().getAppId());
        SysGzh sysGzh = platformSysInfoConfig.getSysGzh();
        String openGroupCode = sysGzh.getOpenGroupCode();
        String springProfilesActive = sysGzh.getGzhCode();

        // 获取微信用户基本信息
        WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);


//        if (springProfilesActive.equals("prodqkb")) {//启客宝
//
//            menuHandler.pushMsg("[握手] 您好，由于公众号升级，请关注新号继续使用\n\n<a href=\"weixin://bizmsgmenu?msgmenucontent=客服&msgmenuid=+++\">\uD83C\uDF37 有任何问题请回复【客服】解答</a>"
//                    , wxMessage.getFromUser(), weixinService);
//
//            String[] gzhArr = {"kdbw_qrcode.png"};
//
//            int index = (int) (Math.random() * gzhArr.length);
//
//            String clickSendImg = platformSysInfoConfig.getWxShareImgPath() + gzhArr[index];
//            menuHandler.mySendKefuImg(wxMessage, weixinService, clickSendImg, 0);
//            return null;
//        }

        String eventKey = wxMessage.getEventKey();

        boolean pushArticle = false;//是否发了文章

        if (userWxInfo != null) {
            // TODO 可以添加关注用户到本地
            //查询用户是否已经存在
            int finalUserId = Optional.ofNullable(userInfoService.getUserStatusByOpenId(userWxInfo.getOpenId())).orElse(0);
            if (finalUserId > 0) { //该openid已存在

                //region 设置用户基本信息
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(finalUserId);
                userInfo.setWxUnionId(userWxInfo.getUnionId());
                //userInfo.setNickName(userWxInfo.getNickname());//getUserService()不再返回头像和昵称
                //userInfo.setUserName(userWxInfo.getNickname());//getUserService()不再返回头像和昵称
                //userInfo.setAvatarUrl(userWxInfo.getHeadImgUrl());
                //userInfo.setAvatarUrl(AliyunOssClientUtil.uploadFileByFileUrl2(userWxInfo.getHeadImgUrl()));//getUserService()不再返回头像和昵称
                userInfo.setConcernStatus(1);
                userInfo.setGzhId(sysGzh.getId());
                if (openGroupCode != null && openGroupCode.trim().length() > 0) {
                    userInfo.setOpenGroupCode(openGroupCode);//开放平台分组标识
                }

                UserInfo curUser = userInfoService.getUserBaseInfo(finalUserId);//看看当前用户有没有 推荐人，没有才 设置，20200303
                if (StringUtils.isNotBlank(eventKey)) {
                    //log.error("*** eventKey:" + eventKey);
                    String referer = StringUtils.split(eventKey, "_")[1];

                    if (curUser != null && (curUser.getReferer() == null || curUser.getReferer() <= 0)) { //看看当前用户有没有 推荐人，没有才 设置，20200303
                        if (StringUtils.isNumeric(referer)) {

                            int refererInt = Integer.parseInt(referer);

                            int refererInDB = Optional.ofNullable(userInfoService.getUserReferer(finalUserId)).orElse(0);

                            //用户不能自己添加自己为推荐人
                            if (refererInDB == 0 && refererInt != finalUserId) {
                                userInfo.setReferer(Integer.parseInt(referer));
                            }
                        }
                    }
                } else {
                    if (curUser != null && (curUser.getReferer() != null && curUser.getReferer() > 0)) {
                        userInfo.setReferer(curUser.getReferer());
                    }
                }

                if (userWxInfo.getSubscribeTime() != null && userWxInfo.getSubscribeTime() > 0) {  //20210126
                    userInfo.setSubscribeTime(DateUtil.timeStampToDate(userWxInfo.getSubscribeTime().toString()));
                }
//                else {
//                    userInfo.setSubscribeTime(DateUtil.getCurDate());
//                }
                userInfo.setModifyTime(DateUtil.getCurDate());

                userInfoService.modifyWxUserInfo(userInfo);
                //endregion

                try {

                    //region 设置用户品牌信息
                    log.info("[SubscribeHandler]_subBrandInfo_up____start:");
                    //int refererInDB = Optional.ofNullable(userInfoService.getUserReferer(finalUserId)).orElse(0);
                    int refererInDB = Optional.ofNullable(userInfo.getReferer()).orElse(0);
                    log.info("[SubscribeHandler]_subBrandInfo_up____refererInDB:" + refererInDB);
                    //添加品牌

                    List<UserBrandCombinedInfo> userBrands = userBrandInfoService.getUserBrandInfo(userInfo.getUserId());
                    log.info("[SubscribeHandler]_subBrandInfo_up____userBrands:" + userBrands.size());
                    if (userBrands == null || userBrands.size() <= 0) {//而且当前用户没有品牌
                        if (refererInDB != 0) { //当推荐人不为空
                            List<UserBrandCombinedInfo> refererBrands = userBrandInfoService.getUserBrandInfo(refererInDB);//找推荐人的品牌
                            log.info("[SubscribeHandler]_subBrandInfo_up____refererBrands:" + refererBrands.size());
                            if (refererBrands != null && refererBrands.size() > 0) {
//                                for (UserBrandCombinedInfo ubc : refererBrands) {
//                                    userBrandInfoService.subBrandInfo(finalUserId, ubc.getBrandId());
//                                    log.info("[SubscribeHandler]_subBrandInfo_up____userId:" + finalUserId + "____brandId:" + ubc.getBrandId());
//                                }
                                userBrandInfoService.copyRefererBrand(finalUserId, refererInDB); //20210519
                            }
//                            else {//当推荐人品牌为空，把用户查看的第一篇文章的品牌 设置给该用户,屏蔽于20210510,只跟推荐人
//                                setUserOneBrandId(finalUserId);
//                            }
                        }
//                        else {//当推荐人为空，把用户查看的第一篇文章的品牌 设置给该用户,屏蔽于20210510,只跟推荐人
//                            setUserOneBrandId(finalUserId);
//                        }
                    }
                    //endregion

                    //region 20210125 hyl 发送推荐人信息
                    if (userInfo.getReferer() != null && userInfo.getReferer() > 0) {
                        UserInfo refererUser = userInfoService.getUserBaseInfo(userInfo.getReferer());
                        if (refererUser != null) {
                            menuHandler.pushMsg(SysConstant.SUBSCRIBE_REFERER_PUSH_MSG.replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain()).replace("[username]", userInfo.getNickName()),
                                    refererUser.getOpenId(), weixinService);
                        }
                    }
                    //endregion 20210125 hyl 发送推荐人信息

                } catch (Exception e) {
                    log.error("[SubscribeHandler]_subBrandInfo_up_error:" + e.getMessage());
                }
            } else {  //该openid 不存在

                //region 设置用户基本信息
                UserInfo userInfo = new UserInfo();
                //userInfo.setNickName(userWxInfo.getNickname());//getUserService()不再返回头像和昵称
                //userInfo.setUserName(userWxInfo.getNickname());//getUserService()不再返回头像和昵称
                //userInfo.setAvatarUrl(userWxInfo.getHeadImgUrl());
                //userInfo.setAvatarUrl(AliyunOssClientUtil.uploadFileByFileUrl2(userWxInfo.getHeadImgUrl()));//getUserService()不再返回头像和昵称
                userInfo.setOpenId(userWxInfo.getOpenId());
                userInfo.setWxUnionId(userWxInfo.getUnionId());

                if (StringUtils.isNotBlank(eventKey)) {
                    //log.error("*** eventKey:"+eventKey);
                    String referer = StringUtils.split(eventKey, "_")[1];

                    if (StringUtils.isNumeric(referer)) {
                        userInfo.setReferer(Integer.parseInt(referer));
                    }
                }

                userInfo.setConcernStatus(1);
                if (userWxInfo.getSubscribeTime() != null && userWxInfo.getSubscribeTime() > 0) {  //20210126
                    userInfo.setSubscribeTime(DateUtil.timeStampToDate(userWxInfo.getSubscribeTime().toString()));
                }
//                else {
//                    userInfo.setSubscribeTime(DateUtil.getCurDate());
//                }
                userInfo.setCreateTime(DateUtil.getCurDate());
                userInfo.setGzhCode(springProfilesActive);//公众号标识
                userInfo.setGzhId(sysGzh.getId());
                if (openGroupCode != null && openGroupCode.trim().length() > 0) {
                    userInfo.setOpenGroupCode(openGroupCode);//开放平台分组标识
                }

                userInfoService.addWxUserInfo(userInfo);
                //endregion

                finalUserId = userInfo.getUserId();

                //region 设置用户附加信息
                //默认添加用户印象
                userAsyncTask.setUserDefaultImpression(userInfo.getUserId());

                //默认添加3个文章关注类型
//                articleAsyncTask.setUserDefaultSubArticleType(userInfo.getUserId());

                //默认20%的等级
                UserPromotionSettleInfo userPromotionSettleInfo = new UserPromotionSettleInfo();
                userPromotionSettleInfo.setUserId(finalUserId);
                userPromotionSettleInfo.setFirstLevelProportion(20);
                userPromotionSettleInfo.setCreateTime(new Date());
                userPromotionSettleInfoService.addPromotionSettleInfo(userPromotionSettleInfo);
                //endregion

                //region 设置用户品牌信息
                try {
                    //如果有推荐人，默认关注推荐人的品牌
                    //int refererInDB = Optional.ofNullable(userInfoService.getUserReferer(finalUserId)).orElse(0);
                    int refererInDB = Optional.ofNullable(userInfo.getReferer()).orElse(0);
                    boolean setUserBrand = false;
                    boolean setUserType = false;
                    if (refererInDB != 0) {
                        List<UserBrandCombinedInfo> userBrands = userBrandInfoService.getUserBrandInfo(refererInDB);
                        if (userBrands != null && userBrands.size() > 0) {
//                            for (UserBrandCombinedInfo ubc : userBrands) {
//                                userBrandInfoService.subBrandInfo(finalUserId, ubc.getBrandId());
//                            }
                            userBrandInfoService.copyRefererBrand(finalUserId, refererInDB); //20210519
                            setUserBrand = true;
                        }
                    }

                    //如果推荐人没有品牌，就找用户看的 最近一个品牌文章 的品牌 ，20201204
                    //20210510 屏蔽，只跟推荐人
//                    if (!setUserBrand) {
//                        setUserBrand = setUserOneBrandId(finalUserId);
//                    }

                    if (!setUserBrand) {//如果品牌没有被设置

                        setUserType = userBrandInfoService.setDefaultBrand(springProfilesActive, finalUserId,0);//20211109 为专业号设置默认品牌，封装起来

                    }

                    // 如果推荐人有关注类型，则关注推荐人的类型；否则，默认关注 3 个类型(财税、正能量、健康养生)
                    if (!setUserType) {
                        // 关注推荐人的类型 2022-03-26
                        UserRelateArticleTypeInfo userRelateArticleTypeInfo = null;
                        if (refererInDB != 0) {
                            userRelateArticleTypeInfo = iUserRelateArticleTypeInfoService.getUserRelateArticleTypeInfo(Integer.valueOf(refererInDB));
                        }

                        if (userRelateArticleTypeInfo != null) {
                            String articleTypeIds = userRelateArticleTypeInfo.getArticleTypeIds();
                            iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, articleTypeIds);
                        } else {
                            iUserRelateArticleTypeInfoService.recordUserRelateArticleTypeInfo(finalUserId, SysConstant.DEFAULT_SUBSCRIBE_ARTICLE_TYPE);// 财税、正能量、健康养生
                        }
                    }
                } catch (Exception e) {
                    log.error("[SubscribeHandler]_subBrandInfo_down_error:" + e.getMessage());
                }
                //endregion

                //region 20201014 处理金牌社交电商 的数据 start

                /*try {
                    if (springProfilesActive != null
                            && (springProfilesActive.equals("prodjpsj"))) { //金牌社交电商才处理
                        String gzhName = "金牌社交电商";

                        Integer isSetData = 0; //0未设置  1已设置

                        String sql = String.format("select id,nickname,vip,viptime,one,credit2 from ims_huo_user where openid='%s' limit 1", userWxInfo.getOpenId());
                        ResultSet rs = jinPaiDataConfig.getStatement().executeQuery(sql);
                        ImportUsersJinPaiInfo importUser = null;
                        if (rs.next()) {
                            importUser = new ImportUsersJinPaiInfo();
                            importUser.setUserId(finalUserId);
                            importUser.setFromUserId(rs.getInt("id"));
                            importUser.setNickName(rs.getString("nickname"));
                            importUser.setVip(rs.getInt("vip"));
                            if (rs.getLong("viptime") > 0) {
                                long r = rs.getLong("viptime") * 1000;
                                Date d = new Date(r);
                                importUser.setVipTime(d);
                            }
                            importUser.setOne(rs.getInt("one"));
                            importUser.setCredit2(rs.getDouble("credit2"));
                            importUser.setCreateTime(new Date());

                        }
                        rs.close();

                        if (importUser != null) {//只有找到一条的时候才处理

                            //修改用户vip状态
                            UserInfo updateVipUser = new UserInfo();
                            updateVipUser.setUserId(finalUserId);
                            updateVipUser.setModifyTime(DateUtil.getCurDate());
                            updateVipUser.setConcernStatus(1);//解决弹出关注的问题
                            updateVipUser.setAccountBalance(importUser.getCredit2());

                            UserVipValidInfo userVipValidInfoInDB = vipInfoService.getVipValidInfo(finalUserId);
                            //如果没有查到购买信息，说明是第一次购买
                            if (userVipValidInfoInDB == null && importUser.getVip().equals(1)) {
                                UserVipValidInfo vipValidInfo = new UserVipValidInfo();
                                vipValidInfo.setUserId(finalUserId);
                                vipValidInfo.setBeginTime(DateUtil.getCurDate());
                                vipValidInfo.setEndTime(importUser.getVipTime());

                                vipValidInfo.setVipLev(1);
                                vipValidInfo.setVipStatus(1);
                                vipValidInfo.setCreateTime(DateUtil.getCurDate());

                                int r1 = vipInfoService.recordUserVipValidInfo(vipValidInfo);

                                //记录购买日志
                                UserVipLogInfo userVipLogInfo = new UserVipLogInfo();
                                userVipLogInfo.setUserId(finalUserId);
                                userVipLogInfo.setVipLev(1);
                                userVipLogInfo.setCreateTime(vipValidInfo.getBeginTime());

                                int r2 = vipInfoService.recordUserVipLogInfo(userVipLogInfo);


                                if (vipValidInfo.getEndTime().getTime() > DateUtil.getCurDate().getTime()) {//还没到期
                                    updateVipUser.setVipStatus(1);
                                }

                                //isSetData = 1;//已设置
                            }
                            int r3 = userInfoService.modifyWxUserInfo(updateVipUser);
                            importUsersJinpaiMapper.add(importUser);
                        }


                    }
                } catch (Exception e) {
                    log.error("[SubscribeHandler]_wxUserLogin_dataSet_error:" + e.getMessage());
                }*/
                //endregion 20201014 处理金牌社交电商 的数据 end
            }

            //region 20200319 添加开放平台用户记录激活处理 start
            //20200410暂时屏蔽，影响数据库性能，待有需要切换时才开启

            //region 20210808 hyl 复制个人信息(启客宝->开单爆文、掌柜推手)
//            log.error("执行updateUserIdByUnionId 开始："+DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS",DateUtil.getCurDate()));
//            try {
//                if (springProfilesActive != null
//                        //&& (springProfilesActive.equals("back_zkt"))) {
//                        && (springProfilesActive.equals("prodkdbw") )) {
//                    //userInfoService.getUserByImg("prodqkb",userWxInfo.getNickname(),userWxInfo.getHeadImgUrl(),finalUserId);
//                    Integer actUserId= userInfoService.updateUserIdByUnionId(userWxInfo,finalUserId,"prodqkb",springProfilesActive);
//                    if(actUserId!=finalUserId) {
//                        finalUserId = actUserId;
//                    }
//                }
//            } catch (Exception e) {
//            }
//            log.error("执行updateUserIdByUnionId 结束："+DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss:SSS",DateUtil.getCurDate()));
            //endregion

            //region （公众号做通）20210902 添加公众号openid与userid映射
            UserGroupGzh userGroupGzh = userGroupGzhService.getUserGroupGzh(springProfilesActive);//查看当前公众号 在不在 公众号组里
            if (userGroupGzh != null && userGroupGzh.getGroupCode() != null ) {
                Integer groupUserId = userGroupGzhService.getUserGroupUserId(springProfilesActive, userWxInfo.getOpenId(), sysGzh.getAppId(), userWxInfo.getUnionId(), userGroupGzh.getGroupCode());
            }
            //endregion


            //region 嫌疑人自动拉黑 start
            try {
                //boolean r = wantedUsersService.checkAvatar(finalUserId, userWxInfo.getNickname());//getUserService()不再返回头像和昵称
                //if (r) {
                  //  userInfoService.setBlockState(finalUserId);
                //}
            } catch (Exception e) {
                log.error("[SubscribeHandler]_setBlockState_error:" + e.getMessage());
            }
            //endregion 嫌疑人自动拉黑 end


            //关注公众号用户，设置接收消息推送缓存
            WxPushUserInfo wxPushUserInfo = new WxPushUserInfo();
            wxPushUserInfo.setUserId(finalUserId);
            wxPushUserInfo.setOpenId(userWxInfo.getOpenId());
            wxPushUserInfo.setCacheTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
            redisCacheUtil.setCacheObject("wxPushUser" + finalUserId, JSON.toJSONString(wxPushUserInfo), 172800);

            //发送用户关注之前需要保存的文章信息
            Object articleIdBeforeSubscribeObj = redisCacheUtil.getCacheObject(finalUserId + "articleIdBeforeSubscribe");
            log.info("[SubscribeHandler]_articleIdBeforeSubscribeObj:" + articleIdBeforeSubscribeObj);

            if (articleIdBeforeSubscribeObj != null) {
                Integer articleIdBeforeSubscribe = (Integer) articleIdBeforeSubscribeObj;
                //20210119 暂时屏蔽 hyl
                //userSaveArticleInfoWxPushAsyncTask.saveArticleInfoWxPushAsyncTask(finalUserId, articleIdBeforeSubscribe, userWxInfo.getOpenId(), springProfilesActive);
            }

            //log.error("******* wxMessage.getScene()："+wxMessage.getScene());
            if (StringUtils.isNotBlank(eventKey)) {//发文章
                String[] sceneArr = StringUtils.split(eventKey, "_");

                //region 推送用户关注进来的文章
                if (sceneArr.length > 2 && !sceneArr[2].equals("null")) {

                    //menuHandler.mySendKefuMessage(wxMessage, weixinService, "已生成带有您名片的文章\n \t\uD83D\uDC47\t\uD83D\uDC47\t\uD83D\uDC47", 0);

                    userSaveArticleInfoWxPushAsyncTask.saveArticleInfoWxPushAsyncTask(finalUserId, Integer.parseInt(sceneArr[2]), userWxInfo.getOpenId(), springProfilesActive);
                    pushArticle = true;
                }
                //endregion

                //region 20200716 添加用户指向
                if (sceneArr.length > 3 && !sceneArr[3].equals("null")) {

                    if (finalUserId != Integer.parseInt(sceneArr[3])) {
                        GzhUserMap cheakGzhUserMap = sysGzhService.checkGzhUserMap(Integer.parseInt(sceneArr[3]), finalUserId);

                        if (cheakGzhUserMap == null) {
                            GzhUserMap gzhUserMap = new GzhUserMap();
                            UserInfo sUser = userInfoService.getUserBaseInfo(Integer.parseInt(sceneArr[3]));//原公众号userid
                            if (sUser != null) {
                                gzhUserMap.setsUserId(sUser.getUserId());
                                gzhUserMap.setsOpenid(sUser.getOpenId());
                                gzhUserMap.setsGzhCode(sUser.getGzhCode());

                                UserInfo tUser = userInfoService.getUserBaseInfo(finalUserId);//原公众号userid
                                gzhUserMap.settUserId(tUser.getUserId());
                                gzhUserMap.settOpenid(tUser.getOpenId());
                                gzhUserMap.settGzhCode(springProfilesActive);

                                if (tUser != null && !tUser.getGzhCode().equals(sUser.getGzhCode())) {
                                    sysGzhService.addGzhUserMap(gzhUserMap);
                                }
                            }
                        }
                    }
                    //userSaveArticleInfoWxPushAsyncTask.saveArticleInfoWxPushAsyncTask(finalUserId, Integer.parseInt(sceneArr[2]), userWxInfo.getOpenId());
                }
                //endregion
            }
        }

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = handleSpecial(wxMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(userWxInfo.getOpenId());

        //region 早晚安、招商页、商学院的链接推送
        try {

            // 20210721 hyl start
            Object cacheObjectPunchClock = redisCacheUtil.getCacheObject("PUNCH_CLOCK" + userInfo.getUserId());
            if (null != cacheObjectPunchClock) {

                Calendar rightNow = Calendar.getInstance();
                int hour = rightNow.get(Calendar.HOUR_OF_DAY);

                String anTxt = "☀早安";
                if (hour > 16) {
                    anTxt = "\uD83C\uDF19晚安";
                }

                PunchClockArticleInfo punchClockArticleInfo = userPunchClockInfoService.getUserPunchClockArticleInfo();

                String kefuMsg = anTxt + "心语已添加您的名片\n\n" +
                        "标题：《" + punchClockArticleInfo.getClockArticleTitle() + "》\n\n" +
                        "\uD83D\uDC49<a href=\"weixin://bizmsgmenu?msgmenucontent=打卡&msgmenuid=+++\">点击这里领取心语</a>\uD83D\uDC48";
                //+"                    \uD83D\uDC47\uD83D\uDC47\uD83D\uDC47";

                menuHandler.mySendKefuMessage(wxMessage, weixinService,
                        kefuMsg, 0);
                redisCacheUtil.removeSingleCache("PUNCH_CLOCK" + userInfo.getUserId());

                pushArticle = true;
            }
            // 20210721 hyl end

            // 20200515 yl start
            Object cacheObject = redisCacheUtil.getCacheObject("STATUS_IS_THREE" + userInfo.getUserId());
            if (null != cacheObject) {
                menuHandler.headMsgPushMsg(userInfo, wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_THREE" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20200515 yl end
            // 20200521 yl start
            Object cache = redisCacheUtil.getCacheObject("STATUS_IS_FOUR" + userInfo.getUserId());
            if (null != cache) {
                menuHandler.extensionMsgPush(wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_FOUR" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20200521 yl end

            // 20200624 hyl start
            Object cache5 = redisCacheUtil.getCacheObject("STATUS_IS_FIVE" + userInfo.getUserId());
            if (null != cache5) {
                menuHandler.exteMsgPush5(wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_FIVE" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20200624 hyl end

            // 20200624 yl start
            Object cache6 = redisCacheUtil.getCacheObject("STATUS_IS_SIX" + userInfo.getUserId());
            if (null != cache6) {
                menuHandler.exteMsgPush6(wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_SIX" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20200624 yl end

            // 20200819 hyl start
            Object cache7 = redisCacheUtil.getCacheObject("STATUS_IS_SEVEN" + userInfo.getUserId());
            if (null != cache7) {
                menuHandler.exteMsgPush7(wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_SEVEN" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20200819 hyl end


            // 20200825 hyl start
            Object cache8 = redisCacheUtil.getCacheObject("STATUS_IS_EIGHT" + userInfo.getUserId());
            if (null != cache8) {
                menuHandler.exteMsgPush8(wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_EIGHT" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20200825 hyl end

            // 20201013 ljt start
            Object cache9 = redisCacheUtil.getCacheObject("STATUS_IS_NINE" + userInfo.getUserId());
            if (null != cache9) {
                Integer fitId = (Integer) cache9;

                menuHandler.exteMsgPush9(wxMessage.getFromUser(), fitId, weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_NINE" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20201013 ljt end

            // 20201208 ljt start 商学院
            Object cache10 = redisCacheUtil.getCacheObject("STATUS_IS_TEN" + userInfo.getUserId());
            if (null != cache10) {
                Integer fitId = (Integer) cache10;

                menuHandler.exteMsgPush10(wxMessage.getFromUser(), fitId, weixinService, platformSysInfoConfig);
                redisCacheUtil.removeSingleCache("STATUS_IS_TEN" + userInfo.getUserId());
                pushArticle = true;
            }
            // 20201208 ljt end 商学院
        } catch (Exception e) {
            log.error("[SubscribeHandler]_setBlockState_error:" + e.getMessage());
        }
        //endregion 招商页的推送

        long sleepCount = 0;
        if (pushArticle) {
            sleepCount = 20000;
        }

        //region 推送欢迎语
        try {
            menuHandler.pushSubscribeMsg(userInfo, wxMessage, weixinService, platformSysInfoConfig, springProfilesActive, sleepCount);
        } catch (Exception e) {
            log.error("[SubscribeHandler]_pushSubscribeMsg_error:" + e.getMessage());
        }

        try {
            if (springProfilesActive != null &&  //专业号不推优惠券，20210120改为 特价号 才不推优惠券
                    professional.contains(springProfilesActive)) {

                if (springProfilesActive.equalsIgnoreCase("prodzx1") ||
                        springProfilesActive.equalsIgnoreCase("prodhyxt") ||
                        springProfilesActive.equalsIgnoreCase("prodhysck") ||
                        springProfilesActive.equalsIgnoreCase("prodshjj") ||
                        springProfilesActive.equalsIgnoreCase("prodshsck") ||
                        springProfilesActive.equalsIgnoreCase("prodbkwz")) {
                    menuHandler.pushCouponProfessionalNew(userInfo,wxMessage, weixinService, platformSysInfoConfig, 20 * 1000);//专业号
                    menuHandler.generalKeFuQrCodePushMsg(wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                    //menuHandler.mySendKefuMessage(wxMessage,weixinService, SysConstant.SUBSCRIBE_PUSH_MSG_3,50*1000);
                } else {
                    menuHandler.professionalToolsPushMsg(userInfo, wxMessage.getFromUser(), weixinService, platformSysInfoConfig, 0);
                    menuHandler.getProfessionalPushMsg(userInfo, wxMessage.getFromUser(), weixinService, platformSysInfoConfig, 0);
                    menuHandler.pushCouponProfessional(wxMessage.getFromUser(), weixinService, platformSysInfoConfig, 1000 * 300);//专业号
                }
            } else {
                //if (!springProfilesActive.equals("prodqkb")) { //除启客宝，其它都是新规
                menuHandler.generalKeFuQrCodePushMsg(wxMessage.getFromUser(), weixinService, platformSysInfoConfig);
                menuHandler.pushCouponProfessional(wxMessage.getFromUser(), weixinService, platformSysInfoConfig, 20 * 1000);

            }
            menuHandler.setBrand3Minutes(springProfilesActive, userInfo.getUserId(),0);//3分钟后如果还没设置品牌，自动设置 hyl 20211109
            menuHandler.pushGiveVip(userInfo.getUserId(), platformSysInfoConfig, 0);
            //}
        } catch (Exception e) {
            log.error("[SubscribeHandler]_pushSubscribeMsg_error:" + e.getMessage());
        }
        //endregion

        //region 20210125 hyl 发送推荐人信息
        try {

            if (userInfo.getReferer() != null && userInfo.getReferer() > 0) {
                UserInfo refererUser = userInfoService.getUserBaseInfo(userInfo.getReferer());
                if (refererUser != null) {
                    menuHandler.pushMsg(SysConstant.SUBSCRIBE_REFERER_PUSH_MSG.replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain()).replace("[username]", userInfo.getNickName()),
                            refererUser.getOpenId(), weixinService);
                }
            }
        } catch (Exception e) {
            log.error("[SubscribeHandler]_pushSubscribeMsg_error:" + e.getMessage());
        }
        //endregion 20210125 hyl 发送推荐人信息


        if (StringUtils.isNotBlank(eventKey)) {

            String sceneStr = "51ai";
            String scene = StringUtils.split(eventKey, "_")[1];
            if (sceneStr.equalsIgnoreCase(scene)) {

                //UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(userWxInfo.getOpenId());
                generateActivityPushMsg(wxMessage, wxMessage.getFromUser(), userInfo, weixinService, platformSysInfoConfig);

            }
        }

        return responseResult;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    protected WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
        //TODO
        return null;
    }

    private void generateActivityPushMsg(WxMpXmlMessage wxMessage, String toUser, UserInfo userInfo, WeixinServiceDL weixinService,PlatformSysInfo platformSysInfoConfig) {

        String articleAccessDomain = platformSysInfoConfig.getFrontDomain();

        try {

            String kefuMsg = "Hi～，劳动的人最美丽～～\n" +
                    "\n" +
                    "\u200D\uD83D\uDE80您的五一证书卖力生成中，请稍后……\n" +
                    "\n" +
                    "也可点击下方链接，进入活动页面生成证书即可保存\n" +
                    "\n" +
                    "<a href='"+ articleAccessDomain +"/#/mayDay'>\uD83D\uDC49戳这里进入活动页面>></a>\n\n";

            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
            }

            WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(toUser).content(kefuMsg).build();
            weixinService.getKefuService().sendKefuMessage(message);

            //下载用户头像
            String avatarName = UUID.randomUUID().toString() + ".jpg";
            ToolUtil.downloadAvatarPic(userInfo.getAvatarUrl(), userInfo.getUserId(), avatarName);

            String avatarPath = SysConstant.WX_AVATAR_DOWNLOAD_PATH + userInfo.getUserId() + "/" + avatarName;

            String telNum = userInfo.getTelNum();
            String desc = null;

            if (StringUtils.isNotBlank(telNum)) {
                desc = "电话: " + userInfo.getTelNum();;
            }

            File resultImg = SharedActivityImageUtils.generate51ActivitySharedImage(avatarPath, null, userInfo.getNickName(), desc);

            WxMediaUploadResult wxMediaUploadResult = weixinService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, resultImg);

            String mediaId = wxMediaUploadResult.getMediaId();

            WxMpKefuMessage activityImgMsg = WxMpKefuMessage.IMAGE().toUser(toUser).mediaId(mediaId).build();
            weixinService.getKefuService().sendKefuMessage(activityImgMsg);


        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
